import {Pressable, View} from 'react-native';
import InfoCard from '../DeviceInfo/DeviceInfoCard';
import DeviceState from '../DeviceInfo/DeviceState';
import React, {useMemo} from 'react';
import {useTranslation} from 'react-i18next';
import {Icon, Text, useAppTheme} from 'tsun-smart-ui';
import {useDeviceInfo} from '../DeviceInfo/DeviceInfoContext';
import {navigationRef} from '@/navigation';
import DeviceAlarm from '../DeviceInfo/DeviceAlarm';
import {template} from '@beqa/react-slots';
import Logo from '../Logo';
export const CardTitle = ({
  title,
  icon,
  power,
  onPress,
}: {
  title: string;
  icon: React.ReactNode;
  power?: number | string;
  onPress?: () => void;
}) => {
  const theme = useAppTheme();
  return (
    <Pressable className="flex-row flex-between" onPress={onPress}>
      <View className="flex-row items-center">
        {icon}
        <Text className=" ml-2" variant="bodyStrong">
          {title}
        </Text>
      </View>
      {onPress && (
        <View className="flex-row items-center gap-x-3">
          <Text
            variant="navTitle"
            style={{
              color: theme.colors?.brand?.primary,
            }}
            className="font-heading">
            {typeof power === 'number' ? power?.toFixed(1) : power}W
          </Text>
          <Icon
            name="right"
            size={10}
            color={theme.colors?.neutral?.primary}></Icon>
        </View>
      )}
    </Pressable>
  );
};
const Inverter = () => {
  const {t} = useTranslation();
  const {
    pvTotalPower,
    pvList,
    outList,
    outPower,
    dayOutPower,
    totalOutPower,
    state: {isConnect},
  } = useDeviceInfo();
  const theme = useAppTheme();
  const memoOutList = useMemo(() => {
    const result = [];
    for (let i = 0; i < (outList ?? []).length; i++) {
      for (let [key, value] of Object.entries(outList[i] ?? {})) {
        if (key !== 'outPower') {
          result.push({
            label:
              t(key === 'outVolt' ? 'syslog.voltage' : 'syslog.current') +
              i +
              1,
            value: value.toFixed(1),
            unit: key === 'outVolt' ? 'V' : 'A',
          });
        }
      }
    }
    return result;
  }, [outList, t]);
  const sections: {
    key: string;
    render: React.ReactNode;
  }[] = [
    {
      key: 'pvPower',
      render: (
        <InfoCard
          title={
            <CardTitle
              title={t('device.pv_power', {defaultValue: '光伏功率'})}
              icon={
                <Logo
                  name="currentTime"
                  round={false}
                  backgroundColor={theme.colors?.brand?.primaryLight!}
                  color={theme.colors?.brand?.primary!}
                />
              }
              onPress={() => {
                navigationRef.navigate('PVChart');
              }}
              power={isConnect ? pvTotalPower ?? '--' : '--'}
            />
          }
          items={(pvList ?? []).map((item, index) => ({
            label: `PV${index + 1}`,
            value: (item.power ?? 0).toFixed(1),
            unit: 'W',
          }))}
        />
      ),
    },
    {
      key: 'outputPower',
      render: (
        <InfoCard
          title={
            <CardTitle
              title={t('device.output_power', {defaultValue: '输出功率'})}
              power={isConnect ? outPower ?? '--' : '--'}
              onPress={() => {
                navigationRef.navigate('EquipTimeChart');
              }}
              icon={
                <Logo
                  name="Output"
                  round={false}
                  backgroundColor={theme.colors?.info?.light!}
                  color={theme.colors?.info?.primary!}
                />
              }
            />
          }
          items={memoOutList}
        />
      ),
    },
    {
      key: 'generation',
      render: (
        <InfoCard
          title={
            <CardTitle
              title={t('device.electricity_production', {
                defaultValue: '发电量',
              })}
              icon={
                <Logo
                  name="Statistics-power"
                  round={false}
                  backgroundColor={theme.colors?.success?.light!}
                  color={theme.colors?.success?.primary!}
                />
              }
            />
          }
          items={[
            {
              label: t('device.today_electricity_production'),
              value:
                dayOutPower > 1000
                  ? (dayOutPower / 1000).toFixed(1)
                  : dayOutPower ?? '--',
              unit: dayOutPower > 1000 ? 'kWh' : 'Wh',
            },
            {
              label: t('device.cumulative'),
              value:
                totalOutPower > 1000
                  ? (totalOutPower / 1000).toFixed(1)
                  : totalOutPower ?? '--',
              unit: totalOutPower > 1000 ? 'kWh' : 'Wh',
            },
          ]}
        />
      ),
    },
  ];
  return (
    <>
      <DeviceState>
        <template.workTime>
          {value => (
            <Text
              style={{
                color: theme.colors?.neutral?.primary,
              }}>
              {t('job.runningTime', {defaultValue: '运行时长'}) + ': '}
              <Text>{value.workTime}</Text>
            </Text>
          )}
        </template.workTime>
      </DeviceState>
      {sections.map(section => (
        <View className="mb-3" key={section.key}>
          {section.render}
        </View>
      ))}
      <DeviceAlarm />
    </>
  );
};
export default Inverter;
